package com.msb;


// 测试链接：https://leetcode.com/problems/add-two-numbers/
public class _11_mid两个链表值相加 {

    // 不要提交这个类
    public static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    // 1.先处理长短都有几个节点, 然后长节点多余的
    // 2.存一个变量作为进位信息
    // 3.最后还进位就新增节点
    public static ListNode addTwoNumbers(ListNode head1, ListNode head2) {
        int length1 = listLength(head1);
        int length2 = listLength(head2);
        ListNode longNode = length1 > length2 ? head1 : head2;
        ListNode shortNode = longNode == head1 ? head2 : head1;
        int addOne = 0;
        ListNode longNext = longNode;
        ListNode shortNext = shortNode;
        ListNode lastOne = null;
        while (shortNext != null) {
            int i = longNext.val + shortNext.val + addOne;
            longNext.val = i % 10;
            addOne = i / 10;
            lastOne = longNext;
            longNext = longNext.next;
            shortNext = shortNext.next;
        }
        while (addOne == 1 && longNext!= null) {
            int i = 1 + longNext.val;
            longNext.val = i % 10;
            addOne = i / 10;
            lastOne = longNext;
            longNext = longNext.next;
        }
        if (addOne == 1) {
            lastOne.next = new ListNode(1);
        }
        return longNode;
    }

    // 求链表长度
    public static int listLength(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }

}